package com.qyc.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @className: QRcodeUtil
 * @Description: 二维码工具类
 * @author: qinyc
 * @date: 2023/6/20 15:36
 * @version: v1.0
 */
@Component
@ConfigurationProperties(prefix = "qrcode")
public class QRcodeUtil {
    //宽度
    private static Integer width;
    //高度
    private static Integer height;
    //存储位置
    private static String path;
    //跳转地址
    private static String url;

    public void setWidth(Integer width) {
        QRcodeUtil.width = width;
    }

    public void setHeight(Integer height) {
        QRcodeUtil.height = height;
    }

    public void setPath(String path) {
        QRcodeUtil.path = path;
    }

    public void setUrl(String url) {
        QRcodeUtil.url = url;
    }

    /**
     * @Author qinyc
     * @Description  生成二维码
     * @version: v1.0
     * @Date 15:40 2023/6/20
     **/
    public static String createQRcode(String content){
        try {
            //1.创建writer对象,用来生成二维码信息
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            //2.生成二维码信息矩阵信息
            Map<EncodeHintType, Object> params = new HashMap<>();
            params.put(EncodeHintType.MARGIN,1);
            params.put(EncodeHintType.CHARACTER_SET,"utf-8");
            /*
             * content:内容
             * BarcodeFormat.QR_CODE ：条码格式为二维码
             * params：矩阵信息
             */
            BitMatrix bitMatrix = multiFormatWriter.encode(url+"?animalId="+content, BarcodeFormat.QR_CODE, width, height, params);
            //3.根据矩阵绘制图形
            BufferedImage image = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
            for (int i = 0; i < width; i++) {
                for (int j = 0; j < height; j++) {
                    //绘制颜色
                    image.setRGB(i,j,bitMatrix.get(i,j)?Color.black.getRGB():Color.white.getRGB());
                }
            }
            //4.创建二维码文件,生成唯一标识文件名
            String fileName = UUID.randomUUID().toString()+".jpg";
            File file = new File(path,fileName);
            //5.将图形信息保存到文件中
            ImageIO.write(image,"jpg",file);
            return fileName;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
